<?php
if (! defined ( 'BASEPATH' ))
	exit ( 'No direct script access allowed' );
class Areas_model extends MY_Model {
	var $table = 'areas_enabled ae';
	public function __construct() {
		parent::__construct ();
	}
	public function getAreasAll() {
		$data = array ();
		$this->db->cache_on ();
		$query = $this->db->select ( 'ae.id, ae.address, ae.district_id, a.name district, ae.city_id, a2.name city, ae.province_id, a3.name province' )->from ( $this->table )->join ( 'areas a', 'ae.district_id=a.id', 'inner' )->join ( 'areas a2', 'ae.city_id=a2.id', 'inner' )->join ( 'areas a3', 'ae.province_id=a3.id', 'inner' )->get ();
		$this->db->cache_off ();
		$rows = $query->result_array ();
		
		if (! empty ( $rows )) {
			foreach ( $rows as $row ) {
				$data [$row ['province_id']] ['province_id'] = $row ['province_id'];
				$data [$row ['province_id']] ['province_name'] = $row ['province'];
				$data [$row ['province_id']] ['city'] [$row ['city_id']] ['city_id'] = $row ['city_id'];
				$data [$row ['province_id']] ['city'] [$row ['city_id']] ['city_name'] = $row ['city'];
				$data [$row ['province_id']] ['city'] [$row ['city_id']] ['district'] [$row ['district_id']] ['district_id'] = $row ['district_id'];
				$data [$row ['province_id']] ['city'] [$row ['city_id']] ['district'] [$row ['district_id']] ['district_name'] = $row ['district'];
				$data [$row ['province_id']] ['city'] [$row ['city_id']] ['district'] [$row ['district_id']] ['areas'] [] = array (
						'building_id' => $row ['id'],
						'building_name' => $row ['address'] 
				);
			}
		}
		return $data;
	}
	public function getAddressName($address_id) {
		$query = $this->db->select ( 'address' )->from ( $this->table )->where ( array (
				'id' => $address_id 
		) )->get ();
		$row = $query->row_array ();
		return empty ( $row ) ? NULL : $row ['address'];
	}
	public function getAreasAll2($areaID) {
		$query = $this->db->select('ae.id,ae.address,a.description')
				->from('areas_enabled ae')
				->join('areas a', 'ae.district_id=a.id', 'left')
				->where('ae.id', $areaID)->get();
		return $query->row_array ();
	}
	
	/**
	 * 更新操作
	 * 
	 * @param array $data        	
	 * @param array $address_id        	
	 */
	public function updateAreas($data, $address_id) {
		$this->db->trans_start ();
		foreach ( $address_id as $a ) {
			$this->db->update ( 'areas_enabled', $data, array (
					'id' => $a 
			) );
		}
		$this->db->trans_complete ();
		return $this->db->trans_status ();
	}
	
	/**
	 * 查找单条信息
	 */
	public function findAreas($address_id, $filed = '*') {
		$query = $this->db->select ( $filed )->where ( array (
				'id' => $address_id 
		) )->from ( $this->table )->get ();
		
		return $query->row_array ();
	}
}